const {
	Service
} = require('uni-cloud-router')
const xlsx = require('../node-xlsx-custom').default
const fs = require('fs')
const moment = require('moment')

module.exports = class StatisticsService extends Service {
	async getMemberBuyCount({
		categoryId,
		pageNum = 1,
		pageSize = 50
	}) {
		const db = this.db
		const dbCmd = db.command
		const $ = dbCmd.aggregate
		let result = {
			total: 0,
			list: []
		}
		if(pageNum == 1) {
			var coll1 = db.collection("t3ds-order").aggregate()
				.match({
					status: dbCmd.gte(3).and(dbCmd.lt(6))
				})
				.unwind('$items')
				.lookup({
					from: 't3ds-mall-goods',
					localField: 'items.goods_id',
					foreignField: '_id',
					as: 'goods'
				})
				.unwind('$goods')
				.lookup({
					from: 't3ds-mall-categories',
					localField: 'goods.category_id',
					foreignField: '_id',
					as: 'category'
				})
				.unwind('$category')
			if (categoryId) {
				coll1 = coll1.match({
					'category._id': categoryId
				})
			}
			let res1 = await coll1.group({
				_id: '$user_id',
				orderCount: $.sum(1),
				ticketCount: $.sum('$items.count')
			})
			.count('total')
			.end()
			if(res1.data.length == 0) {
				return result
			}else {
				result.total = res1.data[0].total
			}
		}
		var coll2 = db.collection("t3ds-order").aggregate()
			.match({
				status: dbCmd.gte(3).and(dbCmd.lt(6))
			})
			.unwind('$items')
			.lookup({
				from: 't3ds-mall-goods',
				localField: 'items.goods_id',
				foreignField: '_id',
				as: 'goods'
			})
			.unwind('$goods')
			.lookup({
				from: 't3ds-mall-categories',
				localField: 'goods.category_id',
				foreignField: '_id',
				as: 'category'
			})
			.unwind('$category')
			if (categoryId) {
				coll2 = coll2.match({
					'category._id': categoryId
				})
			}
			let res2 = await coll2.group({
				_id: '$user_id',
				orderCount: $.sum(1),
				ticketCount: $.sum('$items.count')
			})
			.sort({
				orderCount: -1
			})
			.skip((pageNum - 1) * pageSize)
			.limit(pageSize)
			.lookup({
				from: 't3ds-order',
				let: {
					userId: '$_id'
				},
				pipeline: $
					.pipeline()
					.match(dbCmd.expr($.and([
						$.eq(['$user_id', '$$userId']),
						$.gte(['$status', 3]),
						$.lt(['$status', 6])
					])))
					.unwind('$items')
					.sort({
						pay_time: -1
					})
					.limit(3)
					.project({
						pay_time: 1,
						goods_name: '$items.goods_name'
					})
					.done(),
				as: 'latestOrder'
			})
			.lookup({
				from: 'uni-id-users',
				localField: '_id',
				foreignField: '_id',
				as: 'member'
			})
			.unwind('$member')
			.project({
				id: '$member.id',
				nickname: '$member.nickname',
				mobile: '$member.mobile',
				orderCount: '$orderCount',
				ticketCount: '$ticketCount',
				latestOrder: '$latestOrder'
			})
			.end()
			result.list = res2.data
		return result
	}
	
	//订单统计导出
	async outOrderList({
		categoryId
	}) {
		let result = {}
		let params = {
			pageNum: 1,
			pageSize: 9999
		}
		if(categoryId) {
			params.categoryId = categoryId
		}
		result = await this.getMemberBuyCount(params)
		if(result.list.length < 1) {
			throw new Error("无数据需要导出")
		}
		let s = {
			alignment: {
				horizontal: 'center',
				vertical: 'center'
			}
		}
		let title = [{
			v: '用户昵称（ID）',
			s
		}, {
			v: '手机号',
			s
		}, {
			v: '订单数量',
			s
		}, {
			v: '票券数量',
			s
		}, {
			v: '订单时间',
			s
		}, {
			v: '订单名称',
			s
		}]
		let data = [title]
		result.list.forEach(item => {
			let timeList = ""
			let nameList = ""
			if(item.latestOrder.length > 0) {
				item.latestOrder.forEach(ite => {
					if(!timeList || !nameList) {
						timeList = moment(ite.pay_time).format("YYYY-MM-DD HH:mm:ss")
						nameList = ite.goods_name
					}else {
						timeList = timeList + '\n' + moment(ite.pay_time).format("YYYY-MM-DD HH:mm:ss")
						nameList = nameList + '\n' + ite.goods_name
					}
				})
			}
			let row = [{
					v: item.nickname + '(' + item.id + ')',
					s
				},
				{
					v: item.mobile,
					s
				},
				{
					v: item.orderCount,
					s
				},
				{
					v: item.ticketCount,
					s
				},
				{
					v: timeList,
					s
				},
				{
					v: nameList,
					s
				}]
			data.push(row)
		})
		//console.log("qqq",data)
		let buffer = xlsx.build([{
			name: "sheet",
			data
		}])
		// console.log("wwww",buffer)
		// fs.writeFileSync(`订单统计${Date.now()}.xlsx`, buffer, {
		// 	'flag': 'w'
		// });
		let res = await uniCloud.uploadFile({
			cloudPath: `订单统计${Date.now()}.xlsx`,
			fileContent: buffer
		})
		let {fileID} = res
		if (uniCloud.$provider == 'aliyun') {
			return {
				mpserverlessComposedResponse: true, // 使用阿里云返回集成响应是需要此字段为true
				isBase64Encoded: false,
				statusCode: 301,
				headers: {
					'location': fileID
				}
			}
		} else {
			res = await uniCloud.getTempFileURL({
				fileList: [fileID]
			})
			let {fileList} = res
			return {
				mpserverlessComposedResponse: true, // 使用阿里云返回集成响应是需要此字段为true
				isBase64Encoded: false,
				statusCode: 301,
				headers: {
					'location': fileList[0].download_url
				}
			}
		}
	}
}
